package com.jihe.ehmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihe.common.constant.ProductConstant;
import com.jihe.common.utils.PageUtils;
import com.jihe.common.utils.Query;
import com.jihe.ehmall.product.dao.AttrDao;
import com.jihe.ehmall.product.entity.AttrAttrgroupRelationEntity;
import com.jihe.ehmall.product.entity.AttrEntity;
import com.jihe.ehmall.product.entity.AttrGroupEntity;
import com.jihe.ehmall.product.entity.CategoryEntity;
import com.jihe.ehmall.product.service.AttrAttrgroupRelationService;
import com.jihe.ehmall.product.service.AttrGroupService;
import com.jihe.ehmall.product.service.AttrService;
import com.jihe.ehmall.product.service.CategoryService;
import com.jihe.ehmall.product.vo.AttrCatelogAttrGroupVo;
import com.jihe.ehmall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupService attrGroupService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageBaseByCatId(Map<String, Object> params, Long catId , String type) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type" , "base".equalsIgnoreCase(type) ? 1:0);
        if(catId != 0){
            queryWrapper.eq("catelog_id" , catId);
        }
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and(qw -> {
                qw.like("attr_name" , key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrVo> attrVoList = records.stream().map(item -> {
            AttrVo attrVo = new AttrVo();
            BeanUtils.copyProperties(item, attrVo);
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
            if(attrAttrgroupRelationEntity != null) {
                attrVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                if(attrGroupEntity != null){
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryService.getById(item.getCatelogId());
            if(categoryEntity != null){
                attrVo.setCatelogName(categoryEntity.getName());
            }
            return attrVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrVoList);
        return pageUtils;
    }

    @Override
    @Transactional
    public void saveDetail(AttrCatelogAttrGroupVo attrCatelogAttrGroupVo) {
        //保存属性信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrCatelogAttrGroupVo , attrEntity);
        this.save(attrEntity);
        //保存属性和属性分组的关联信息
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        attrAttrgroupRelationEntity.setAttrGroupId(attrCatelogAttrGroupVo.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrSort(attrCatelogAttrGroupVo.getShowDesc());
        attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

    }

    @Override
    @Transactional
    public void updateDetail(AttrCatelogAttrGroupVo attrCatelogAttrGroupVo) {
        //修改属性信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrCatelogAttrGroupVo , attrEntity);
        this.updateById(attrEntity);
        //根据属性id查询关联关系是否存在,如果不存在就新增,否则就更新
        Integer count = attrAttrgroupRelationService.getBaseMapper().selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrCatelogAttrGroupVo.getAttrId()));
        if(count > 0){
            //根据属性分组id修改属性分组信息
            UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("attr_group_id" , attrCatelogAttrGroupVo.getAttrGroupId());
            updateWrapper.eq("attr_id" , attrCatelogAttrGroupVo.getAttrId());
            attrAttrgroupRelationService.update(updateWrapper);
            return;
        }
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrCatelogAttrGroupVo.getAttrId());
        attrAttrgroupRelationEntity.setAttrGroupId(attrCatelogAttrGroupVo.getAttrGroupId());
        attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

    }

    @Override
    public AttrCatelogAttrGroupVo getAttrInfoAll(Long attrId) {
        //根据属性id查询属性详细信息
        AttrCatelogAttrGroupVo attrInfoVo = new AttrCatelogAttrGroupVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity , attrInfoVo);
        //根据分类id查询属性相关的分类路径
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrInfoVo.setCatelogPath(catelogPath);

        //根据属性id查询相关的属性分组名称
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id" , attrId);
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(queryWrapper);
        if(relationEntity != null) {
            attrInfoVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity groupEntity = attrGroupService.getById(attrInfoVo.getAttrGroupId());
            if(groupEntity != null) {
                attrInfoVo.setAttrGroupName(groupEntity.getAttrGroupName());
            }
        }
        return attrInfoVo;
    }

    @Override
    @Transactional
    public void removeDetailByIds(List<Long> asList) {
        this.removeByIds(asList);
        asList.forEach(attrId ->{
            attrAttrgroupRelationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id" , attrId));
        });
    }

    @Override
    public List<AttrEntity> queryPageAttrRelation(Long attrGroupId) {
        //根据属性分组id查询属性关联信息
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> attrIds = relationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        List<AttrEntity> attrEntities = this.baseMapper.selectBatchIds(attrIds);

        return attrEntities;
    }

    @Override
    public PageUtils queryPageNoAttrRelation(Map<String, Object> params, Long attrGroupId) {
        //根据分组id查询所属分类的所有属性分组
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
        List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()));
        List<Long> attrGroupIds = attrGroupEntities.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrAttrgroupRelationEntity> relationEntityQueryWrapper = new QueryWrapper<>();
        relationEntityQueryWrapper.in("attr_group_id" ,attrGroupIds);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(relationEntityQueryWrapper);
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type" , ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrAttrgroupRelationEntities != null && attrAttrgroupRelationEntities.size() > 0){
            List<Long> attrIds = attrAttrgroupRelationEntities.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());

            if(attrIds != null && attrIds.size() > 0){
                queryWrapper.notIn("attr_id", attrIds);
            }
            String key = (String) params.get("key");
            if(StringUtils.isNotEmpty(key)){
                queryWrapper.and(wrapper -> {
                    wrapper.like("attr_name" , key);
                });
            }
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params) , queryWrapper);
        return new PageUtils(page);

    }


}